package org.example.springoauth2.securitycommon.config.authenticate.grant.wx;

import lombok.AllArgsConstructor;
import org.example.springoauth2.securitycommon.service.SysUserService;
import org.example.springoauth2.securitycommon.util.SecurityUtil;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @author hzq
 * @since 2021-09-12
 */
@AllArgsConstructor
public class WxAuthenticationProvider implements AuthenticationProvider {

    private final SysUserService sysUserService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        // authentication instanceof from WxAuthenticationToken

        String wxOpenid = SecurityUtil.obtainOpenidByPrincipal(authentication.getPrincipal());

        UserDetails userDetails = sysUserService.loadUserByWxOpenid(wxOpenid);

        WxAuthenticationToken token = new WxAuthenticationToken(userDetails);

        token.setDetails(authentication.getDetails());

        return token;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.isAssignableFrom(WxAuthenticationToken.class);
    }
}
